package com.lzw.breezeNovel.webApp.service.impl.comic;

import com.lzw.breezeNovel.model.entity.pojo.comic.ComicChapter;
import com.lzw.breezeNovel.model.entity.query.PaginationResultQuery;
import com.lzw.breezeNovel.webApp.mapper.comic.ComicChapterMapper;
import com.lzw.breezeNovel.webApp.service.comic.ComicChapterService;
import com.lzw.breezeNovel.webApp.vo.comic.ComicChapterVo;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.impl.comic
 * @date 2025/3/16
 * @description 章节
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class ComicChapterServiceImpl implements ComicChapterService {

    /**
     * 注入章节mapper
     */
    @Autowired
    private ComicChapterMapper comicChapterMapper;
    @Override
    @Transactional(readOnly = true)
    public PaginationResultQuery<ComicChapterVo> list(Long comicId, Integer pageNum, Integer pageSize) {
        // 计算分页起始位置
        Integer start = getStart(pageNum, pageSize);

        // 查询章节总数
        Long count = comicChapterMapper.selectCountByComicId(comicId);

        // 如果没有数据，直接返回空结果
        if (count == 0) {
            return new PaginationResultQuery<>(0, pageSize, pageNum, 0, Collections.emptyList());
        }

        // 分页查询章节列表
        List<ComicChapter> comicChapters = comicChapterMapper.selectByComicId(comicId, start, pageSize);

        // 拷贝数据到 VO
        List<ComicChapterVo> comicChapterVoList = copyToVoList(comicChapters);

        return new PaginationResultQuery<>(Math.toIntExact(count), pageSize, pageNum, comicChapterVoList.size(), comicChapterVoList);
    }

    /**
     * 将 ComicChapter 列表拷贝到 ComicChapterVo 列表
     * @param comicChapters 漫画章节列表
     * @return 拷贝后的 VO 列表
     */
    private List<ComicChapterVo> copyToVoList(List<ComicChapter> comicChapters) {
        if (comicChapters == null || comicChapters.isEmpty()) {
            return Collections.emptyList();
        }
        return comicChapters.stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());
    }

    /**
     * 将单个 ComicChapter 转换为 ComicChapterVo
     * @param comicChapter 漫画章节
     * @return 转换后的 VO
     */
    @NotNull
    private ComicChapterVo convertToVo(ComicChapter comicChapter) {
        ComicChapterVo vo = new ComicChapterVo();
        BeanUtils.copyProperties(comicChapter, vo);
        // 处理章节内容
        handleChapterContent(comicChapter, vo);
        // 处理时间格式化
        handleCreateTime(comicChapter, vo);
        return vo;
    }

    /**
     * 处理章节内容
     * @param comicChapter 漫画章节
     * @param vo VO 对象
     */
    private void handleChapterContent(@NotNull ComicChapter comicChapter, ComicChapterVo vo) {
        String content = comicChapter.getContent();
        if (content != null && !content.isEmpty()) {
            String[] splitContent = content.split(",");
            vo.setContent(splitContent);
        }
    }

    /**
     * 处理创建时间的格式化
     * @param comicChapter 漫画章节
     * @param vo VO 对象
     */
    private void handleCreateTime(@NotNull ComicChapter comicChapter, ComicChapterVo vo) {
        Date createTime = comicChapter.getCreateTime();
        if (createTime != null) {
            LocalDateTime localDateTime = createTime.toInstant()
                    .atZone(ZoneId.of("Asia/Shanghai")) // 指定时区
                    .toLocalDateTime();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            vo.setData(formatter.format(localDateTime));
        }
    }
    /**
     * 计算分页数据
     */
    @NotNull
    private Integer getStart(Integer pageNo, Integer size) {
        // 对分页参数进行校验，使用Optional简化代码
        pageNo = Optional.ofNullable(pageNo).orElse(1);
        size = Optional.ofNullable(size).orElse(10);
        pageNo = Math.max(pageNo, 1);
        size = Math.max(size, 1);
        return (pageNo - 1) * size;
    }

}
